package com.aabte.auth.account.infrastructure.persistence;


import com.aabte.auth.account.domain.model.Account;
import com.aabte.auth.account.domain.model.AccountId;
import com.aabte.auth.account.domain.model.AccountName;
import com.aabte.auth.account.domain.model.Password;
import com.aabte.auth.account.domain.repository.AccountRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Optional;
import java.util.UUID;

@Component
public class AccountRepositoryHibernate implements AccountRepository {

    @Resource
    private AccountDAO accountDAO;

    @Override
    public Optional<Account> find(AccountId accountId) {
        return accountDAO.findByAccountId(accountId);
    }

    @Override
    public Optional<Account> find(AccountName accountName) {
        return accountDAO.findByAccountName(accountName);
    }

    @Transactional(readOnly = true)
    @Override
    public Optional<Account> find(AccountName accountName, Password password) {
        return accountDAO.findByAccountNameAndAccountPassword(accountName, password);
    }

    @Override
    public Page<Account> find(Pageable pageable) {
        return accountDAO.findAll(pageable);
    }

    @Override
    public AccountId nextAccountId() {
        return new AccountId(UUID.randomUUID().toString().replaceAll("-", ""));
    }

    @Override
    public void addOrUpdate(Account account) {
        accountDAO.save(account);
    }
}
